package middleware

import (
	"gin.project.template/common/constant"
	"gin.project.template/util/jwt"
	"gin.project.template/util/response"
	"github.com/gin-gonic/gin"
	"strings"
)

func JWTAuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.Request.Header.Get("Authorization")
		if len(authHeader) == 0 {
			response.NotAuth(c)
			c.Abort()
			return
		}

		authList := strings.Split(authHeader, " ")
		if len(authList) != 2 || authList[0] != constant.TokenPrefix {
			response.NotAuth(c)
			c.Abort()
			return
		}
		_, err := jwt.ParseToken(authList[1])
		if err != nil {
			response.NotAuth(c)
			c.Abort()
			return
		}
		c.Next()
	}
}
